package httpServices

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"io"
	"main/Ethernet"
	"main/mobileModule"
	"main/webroot"
	"net/http"
	"os"
	"sort"
	"strconv"
	"time"
)

func RouterWeb(port string) {

	router := gin.Default()
	gin.SetMode(gin.ReleaseMode)
	//gin.SetMode(gin.DebugMode)

	router.StaticFS("/webroot", http.FS(webroot.WebrootFS))
	//exeCurDir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
	//router.StaticFs("/assets", "assets")
	//router.StaticFile("/", "index.html")
	//router.StaticFile("/favicon.ico", "favicon.ico")
	//router.StaticFile("/logo.png", "logo.png")
	//router.StaticFile("/favicon.ico", exeCurDir+"/webroot/favicon.ico")
	//router.StaticFile("/logo.png", exeCurDir+"/webroot/logo.png")

	mobileRouter := router.Group("/api/v1/mobileModule")
	{
		mobileRouter.GET("/info", ApiGetMobileInfoParam)

		mobileRouter.PUT("/info", ApiModifyMobileInfo)
		mobileRouter.GET("/time", ApiGetMobileInfoTime)
	}
	systemRouter := router.Group("/api/v1/system")
	{
		systemRouter.GET("/time", ApiGetMobileInfoTime)
	}

	networkRouter := router.Group("/api/v1/network")
	{
		networkRouter.POST("/param", ApiAddNetwork)

		networkRouter.PUT("/param", ApiModifyNetwork)

		networkRouter.DELETE("/param", ApiDeleteNetwork)

		networkRouter.GET("/params", ApiGetNetworkParams)

		networkRouter.GET("/names", ApiGetNetworkNames)

	}

	restart := router.Group("/api/v1")
	{
		restart.GET("/restart", func(context *gin.Context) {
			context.JSON(http.StatusOK, gin.H{
				"Code":    "1",
				"Message": "关闭进程",
				"Data":    "",
			})
			fmt.Printf("关闭进程\r\n")
			os.Exit(0)
		})

	}
	router.GET("/", func(c *gin.Context) {
		// 如果你已经嵌入了整个 webroot 目录
		file, err := webroot.WebrootFS.Open("index.html") // 注意路径可能需要根据你的实际嵌入路径调整
		if err != nil {
			c.Status(http.StatusInternalServerError)
			return
		}
		defer file.Close()

		// 设置 MIME 类型
		c.Header("Content-Type", "text/html")

		// 发送文件内容给客户端
		_, err = io.Copy(c.Writer, file)
		if err != nil {
			c.Status(http.StatusInternalServerError)
			return
		}
	})

	err := router.Run(port)
	if err != nil {
		fmt.Printf("gin启动错误 %v\r\n", err)
		os.Exit(0)
	}
}

func ApiGetMobileInfoParam(context *gin.Context) {
	//重启时跳过，防止网口被占用
	if mobileModule.MobileModuleResetFlag != 1 {
		mobileModule.MobileModule.MobileModuleGetParam()
	}
	context.JSON(http.StatusOK, gin.H{
		"code":    "0",
		"message": "读取参数成功",
		"data":    mobileModule.MobileModule,
	})
}
func ApiModifyMobileInfo(context *gin.Context) {
	fmt.Printf("\n开始打印:\n%v\n", mobileModule.MobileModule)

	if err := context.ShouldBindJSON(&mobileModule.MobileModuleParam); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})

		return
	}
	fmt.Printf("\n打印接收数据:\n%v\n", mobileModule.MobileModuleParam)
	//if err := context.ShouldBindJSON(&MobileModule); err != nil {
	//	context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
	//	return
	//}
	if err := mobileModule.ModifyMobileModuleParam(mobileModule.MobileModuleParam); err != nil {
		fmt.Printf("\n修改失败:\n%v\n", mobileModule.MobileModule)
		return
	}

	fmt.Printf("\n开始打印:\n%v\n", mobileModule.MobileModule)
}
func ApiGetMobileInfoTime(context *gin.Context) {
	now := time.Now()
	duration := now.Sub(mobileModule.Past)
	days := int(duration.Hours()) / 24
	hours := int(duration.Hours()) % 24
	minutes := int(duration.Minutes()) % 60
	seconds := int(duration.Seconds()) % 60
	WorkTime := strconv.Itoa(days) + "天" + strconv.Itoa(hours) + "时" + strconv.Itoa(minutes) + "分" + strconv.Itoa(seconds) + "秒"
	context.JSON(http.StatusOK, gin.H{
		"code":    "0",
		"message": "读取参数成功",
		"data":    WorkTime,
	})
}
func ApiAddNetwork(context *gin.Context) {

	networkParam := Ethernet.NetworkConfigParamTemplate{}

	err := context.ShouldBindJSON(&networkParam)
	if err != nil {
		fmt.Printf("增加网卡偏好设置JSON格式化错误 %v\n", err)
		context.JSON(http.StatusOK, gin.H{
			"code":    "1",
			"message": "增加网卡偏好设置JSON格式化错误",
			"data":    "",
		})
		return
	}

	err = Ethernet.AddNetworkConfigParam(networkParam)
	if err != nil {
		context.JSON(http.StatusOK, gin.H{
			"code":    "1",
			"message": err.Error(),
			"data":    "",
		})
	} else {
		context.JSON(http.StatusOK, gin.H{
			"code":    "0",
			"message": "增加网卡偏好设置成功",
			"data":    "",
		})
	}
}
func ApiModifyNetwork(context *gin.Context) {

	networkParam := Ethernet.NetworkConfigParamTemplate{}

	err := context.ShouldBindJSON(&networkParam)
	if err != nil {
		fmt.Printf("修改网卡偏好设置JSON格式化错误 %v\n", err)
		context.JSON(http.StatusOK, gin.H{
			"code":    "1",
			"message": "",
			"data":    "",
		})
		return
	}

	err = Ethernet.ModifyNetworkConfigParam(networkParam)
	if err != nil {
		context.JSON(http.StatusOK, gin.H{
			"code":    "1",
			"message": err.Error(),
			"data":    "",
		})
	} else {
		context.JSON(http.StatusOK, gin.H{
			"code":    "0",
			"message": "修改网卡偏好设置成功",
			"data":    "",
		})
	}
}
func ApiDeleteNetwork(context *gin.Context) {

	param := struct {
		Name string `json:"name"`
	}{}

	err := context.ShouldBindJSON(&param)
	if err != nil {
		fmt.Printf("删除网卡偏好设置JSON格式化错误 %v\n", err)
		context.JSON(http.StatusOK, gin.H{
			"code":    "1",
			"message": "",
			"data":    "",
		})
		return
	}

	err = Ethernet.DeleteNetworkConfigParam(param.Name)
	if err != nil {
		context.JSON(http.StatusOK, gin.H{
			"code":    "1",
			"message": err.Error(),
			"data":    "",
		})
	} else {
		context.JSON(http.StatusOK, gin.H{
			"code":    "0",
			"message": "删除网卡偏好设置成功",
			"data":    "",
		})
	}
}
func ApiGetNetworkParams(context *gin.Context) {

	params := Ethernet.GetNetworkParams()

	//排序，方便前端页面显示
	sort.Slice(params, func(i, j int) bool {
		iName := params[i].Index
		jName := params[j].Index
		return iName < jName
	})

	context.JSON(http.StatusOK, gin.H{
		"code":    "0",
		"message": "获取网卡信息成功",
		"data":    params,
	})
}
func ApiGetNetworkNames(context *gin.Context) {

	context.JSON(http.StatusOK, gin.H{
		"code":    "0",
		"message": "获取成功",
		"data":    Ethernet.GetNetworkNames(),
	})
}
